﻿using eslib.HttpApiClient;
using eslib.tools.config;

namespace ArticleClientLib
{
    public class ArticleApi
    {
        public string BaseUrl => apicfg.Instance.apiUrl;

        #region 管理员账号

        /// <summary>
        /// 设置api用的账号
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        public static void SetAdminAccount(string user, string pass)
        {
            _user = user;
            _pass = pass;
        }

        static string user
        {
            get
            {
                if (_user == null) throw new Exception("未进行登录验证");
                return _user;
            }
        }
        static string? _user = null;

        static string pass
        {
            get
            {
                if (_pass == null) throw new Exception("未进行登录验证");
                return _pass;
            }
        }
        static string? _pass = null;
        #endregion

        public async Task<(bool res, string data)> Version()
        {
            ApiClient api = new ApiClient(BaseUrl);
            return await api.GetAsync();
        }



        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        /// <exception cref="Exception">api调用失败时引发</exception>
        public async Task<bool> Login(string user, string pass)
        {
            ApiClient api = new ApiClient(BaseUrl);

            // /Bot/ArticleSysLog/{user}/{pass}
            (bool success, string data) res = await api.GetAsync("ArticleSysLog", user, pass);
            if (!res.success) throw new Exception("api ArticleSysLog调用失败");

            (bool res, string msg, ObjectJsonResult? data) ores = getApiResult(res);

            return ores.data.success;
        }




        /// <summary>
        /// 单个软文同步
        /// </summary>
        /// <param name="articleId"></param>
        /// <returns></returns>
        public async Task<(bool res, string msg, ArticleSyncJson? json)> SyncArticle(long articleId)
        {
            ApiClient api = new ApiClient(BaseUrl);

            //  /Bot/SyncArticle/{account}/{pass}/{articleId}
            (bool success, string data) res = await api.GetAsync("SyncArticle", user, pass, $"{articleId}");
            (bool res, string msg, JsonResult<ArticleSyncJson>? data) jres = getApiResult<ArticleSyncJson>(res);
            if (!jres.res) return (false, jres.msg, null);
            else
                return (jres.res, jres.msg, jres.data.data);
        }







        /// <summary>
        /// 获取子分类
        /// </summary>
        /// <param name="classiflyId"></param>
        /// <returns></returns>
        public async Task<(bool res, string msg, List<ClassiflyJson>? idColl)> GetSubClassifly(long classiflyId)
        {
            ApiClient api = new ApiClient(BaseUrl);

            // /Bot/GetSubClassifly/{classiflyId}
            var res = getApiResult<List<ClassiflyJson>>(await api.GetAsync("GetSubClassifly", $"{classiflyId}"));

            if (res.res)
            {
                var data = res.data;
                if (data.success)
                {
                    return (true, "", data.data);
                }
                else return (false, data.msg, null);
            }
            else return (false, res.msg, null);
        }



        /// <summary>
        /// 获取分类下文章id集合
        /// </summary>
        /// <param name="classiflyId"></param>
        /// <returns></returns>
        public async Task<(bool res, string msg, List<long>? idColl)> GetClassiflyArticleIdCollection(long classiflyId)
        {
            ApiClient api = new ApiClient(BaseUrl);

            // /Bot/GetClassiflyArticleIdCollection/{id}
            var res = getApiResult<List<long>>(await api.GetAsync("GetClassiflyArticleIdCollection", $"{classiflyId}"));

            if (res.res)
            {
                var data = res.data;
                if (data.success)
                {
                    return (true, "", data.data);
                }
                else return (false, data.msg, null);
            }
            else return (false, res.msg, null);
        }


        public async Task<(bool res, string msg, ObjectJsonResult? data)> AddGenericArticle(long classiflyId, LocalArticle art)
        {
            ApiClient api = new ApiClient(BaseUrl);

            // /Bot/AddGenericArticle/{account}/{pass}/{classiflyId}/{name}/{author}/{context}
            string source = string.IsNullOrEmpty(art.Article.author) ? "none" : art.Article.author;
            string ctx = string.IsNullOrEmpty(art.Article.content) ? "none" : art.Article.content;

            var res = await api.GetAsync("AddGenericArticle", user, pass, $"{classiflyId}", art.Article.title, source, ctx);
            return getApiResult(res);
        }



        public async Task<(bool res, string msg, ObjectJsonResult? data)> RemoveGenericArticle(LocalArticle art)
        {
            ApiClient api = new ApiClient(BaseUrl);

            // /Bot/RemoveGenericArticle/{account}/{pass}/{articleId}

            var res = await api.GetAsync("RemoveGenericArticle", user, pass, $"{art.GetDirArticleId()}");
            return getApiResult(res);
        }



        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="json"></param>
        /// <param name="articleId"></param>
        /// <returns></returns>
        public async Task<(bool res, string msg, ObjectJsonResult? data)> ArticleImageUpload(ArticleImageJson json, long articleId)
        {
            //    ArticleImageUpload/{account}/{pass}/{articleId}
            //json:
            //{
            //  "extName": "string",
            //  "buffer": "string"
            //}
            ApiClient api = new ApiClient(BaseUrl);
            var res = await api.PostAsync(json.ToJson(), "ArticleImageUpload", user, pass, articleId);
            return getApiResult(res);

            //返回
            //{ "success":true,"errcode":0,"msg":"","data":{ "image":"/articleImages/1000/test.jpg"} }
        }


        private (bool res, string msg, ObjectJsonResult? data) getApiResult((bool success, string data) res)
        {
            if (!res.success) return (false, "api调用异常,data:" + res.data, null);
            ObjectJsonResult jres = ObjectJsonResult.FromString(res.data);
            return (true, "", jres);
        }


        private (bool res, string msg, JsonResult<T>? data) getApiResult<T>((bool success, string data) res)
        {
            if (!res.success) return (false, "api调用异常,data:" + res.data, null);
            JsonResult<T> jres = JsonResult<T>.FromString(res.data);
            return (true, "", jres);
        }

    }
}